import axios from 'axios'
import Vue from 'vue'
import aggregation from './aggregation'

// let token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NjUyNTI2NTUsIm5pY2tfbmFtZSI6ImtuaWdodHN0YXI4ODgiLCJzaWduIjoiYmZiOTE4MTQ0ZGIyZWFhNTJiZDU2Yzc4NzQ0NWJkZWQiLCJ1aWQiOjY3MTk2MjF9.AH5IVCBfwuydvhbn0LmxbII2mCZpQw4lXsblrg2tXzA';
//localStorage.getItem('cvn_token') || ''
let shopUrlReg = /\/index.php/
let routerUrlReg = /rrysapi.com/
Vue.prototype.axios = axios

const service = axios.create({
  baseURL: '', // api的base_url
  timeout: 20000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    let url = config.url
    if(!shopUrlReg.test(url) && !routerUrlReg.test(url) && window['appToken']){
      config.headers.common['Authorization'] = window['appToken']
    }
    return config
  },
  error => {
    //console.log('err' + error)
    Promise.reject(error)
  }
)

// respone interceptor
service.interceptors.response.use(
  response => {
    const res = response.data

    if (res.status == 1 || res.success == 1) {
      return response.data
    } else {
      if(res.status == 3){
        aggregation.$emit('session.expire', '')
      }
      return Promise.reject(res)
    }
  },
  error => {
    if(error.code == 'ECONNABORTED' && error.message.indexOf('timeout')!=-1){
      aggregation.$emit('session.timeout', '')
    }
    let {response} = error
    if(response && response.status && response.statusText){
      error.info = response.status + ' ' + response.statusText
    }
    return Promise.reject(error)
  }
)

export default service
